const Component = (function () {

    let Component = function () {};
    let _this = Component.prototype;

    //=include ../../common/js/extends/Component.js

    _this.header = function (data = {}) {
        let _data = Object.assign({
            avatar: Config.default_avatar,
            name: "",
            mobile: "",
            class_name: "",
            grade_name: "",
            approval_identity: ""
        }, data);

        let DOM = Render.create(`<div class="header">
            <div class="header-box">
                <div class="header--avatar skeleton">
                    <img src="${_data.avatar}" alt="" srcset="">
                </div>
                <div class="header--info">
                    <div class="header--info-name skeleton">
                        <span class="header--info-name-username">${_data.name}</span>
                        <span class="header--info-name-gcname">${(_data.approval_identity == '0' ? ('（' + _data.grade_name + ' ' + _data.class_name + '）') : '')}</span>
                    </div>
                    <div class="header--info-tel skeleton">${_data.mobile}</div>
                </div>
            </div>
        </div>`);


        return {
            el: DOM
        };
    };

    _this.info = function (data = {}) {
        let _data = Object.assign({
            info: [],
            status: "",
            onClickEdit: function () {}
        }, data);

        let DOM = Render.create(`<div class="info"><div class="info-box"></div></div>`);
        let $Info_box = $(DOM).find(".info-box");
        let info_items = [];

        Object.defineProperty(data, "info", {
            get: function () {
                return _data.info;
            },
            set: function (val) {
                _data.info = val;
            }
        });

        _data.info.map(info => {
            let _info = {
                display: info.display
            };

            let infoItemDOM;

            switch (info.type) {
                case "text":
                case "options":
                case "multiOptions":  
                case "image":
                case "sign":
                case "netdisk":
                case "tel":
                case "id":
                case "address":
                    //只展示非隐藏项
                    if (!info.is_hidden) {
                        infoItemDOM = _this.infoItemText(info, _data.onClickEdit);
                    }
                    break;
                case "part":
                    infoItemDOM = _this.infoItemPart(info, _data.onClickEdit);
                    break;
            }

            if (infoItemDOM != undefined) {
                info_items.push(infoItemDOM.el);
            }
        });

        $Info_box.append(info_items);

        return {
            el: DOM
        };
    };

    _this.infoItemText = function (data, onClickEdit) {
        let _data = Object.assign({
            id: "",
            type: "",
            title: "",
            value: "",
            value_text: "",
            is_hidden: "",
            editable: false,
            display: false
        }, data);

        let color = data.original.color;

        // 编译文字为特殊类型需要显示的方式
        let compile = function (type, value_text, original, value) {
            switch(type + "") {
                case "sign":
                case "image":
                    if (value_text != "") {
                        let figureDOM = value_text.split(",").map(src => {
                                return Render.create(`<figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
                                    <a href="${src}" itemprop="contentUrl" data-size="1640x1136">
                                        <img src="${src}" itemprop="thumbnail" alt="" />
                                    </a>
                                </figure>`);
                        });
                        let figureBoxDOM = Render.create(`<div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery"></div>`);
                        $(figureBoxDOM).append(figureDOM);
                        $(figureBoxDOM).find("img").on("load", function () {
                            $(this).parent().attr("data-size", `${this.naturalWidth}x${this.naturalHeight}`);
                        });

                        window.initPhotoSwipeFromElements([figureBoxDOM]);

                        return figureBoxDOM;
                    } else {
                        return "";
                    }
                case "netdisk":
                    if (value_text != "") {
                        try {
                            let files = JSON.parse(value);
                            let figureBoxDOM = Render.create(`<div></div>`);
                            let previewDom = Render.create(`<div id="previewContent" class="content"></div>`);
                            previewDom.style.cssText = "overflow: hidden;background-color: #404040;position: fixed;z-index: 10;top: 0;left: 0;width: 100%;height: 100%;"
                            let figureDOMs = files.map(file => {
                                let DescDOM = Render.create(`<div class="info--item-desc-netdisk">
                                    <div>
                                        <img src="${file.icon}" alt="" />
                                        <p>${file.name}</p>
                                    </div>
                                </div>`);

                                DescDOM.addEventListener("click", function () {
                                    let rowkey = file.rowkey;
                                    let preview_url = file.preview;
                                    let name = file.name;
                                    let url = `/shijiwxy/weixin/html/teacher/previewFile/index.html?nodownload=1&fileUrl=${preview_url}&rowkey=${rowkey}&fileName=${encodeURIComponent(name)}`

                                    location.hash = rowkey;
                                    previewDom.innerHTML = "";

                                    let iframe = Render.create(`<iframe id="activePage"></iframe>`);
                                        iframe.src = url;
                                        iframe.width = '100%';
                                        iframe.style.height = '100%';
                                        iframe.style.border = "none";
                                        iframe.marginwidth = '0';
                                        iframe.marginheight = '0';
                                        iframe.hspace="0";
                                        iframe.vspace="0";
                                        iframe.frameborder="0";
                                        previewDom.appendChild(iframe);

                                    document.body.appendChild(previewDom);
                                    
                                    let windowPreviewHashChangeEventCallback = function () {
                                        if (location.hash.slice(1) != rowkey) {
                                            document.body.removeChild(previewDom);
                                            window.removeEventListener("hashchange", windowPreviewHashChangeEventCallback);
                                        }
                                    };

                                    window.addEventListener("hashchange", windowPreviewHashChangeEventCallback);
                                });


                                return DescDOM;
                            });

                            $(figureBoxDOM).append(figureDOMs);

                            return figureBoxDOM;
                        } catch (error) {
                            return "";
                        }
                    }
                    return "";
                default:
                    // 说明文字
                    if (original.type == "9") {
                        if (original.url) {
                            value_text = `<a href="${original.url}" style="color:${original.color}">${original.placeholder}</a>`;
                        } else {
                            value_text = `<span style="color:${original.color}">${original.placeholder}</span>`;
                        }
                    }
                    // 手机号
                    if (original.type == "31") {
                        value_text = `<a href="tel:${value}" style="text-decoration:underline;">${value}</a>`;
                    }
                    // 温度输入框
                    if (original.type == "33") {
                        if (+value > +original.warning) {
                            value_text = `<span style="color: red">${value_text}</span>`;
                        } else {
                            value_text = `<span>${value_text}</span>`;
                        }
                    }
                    return value_text;
            }
        };

        let DOM = Render.create(`<div class="info--item">
            <div class="info--item-title skeleton">${_data.title}：</div>
            <div class="info--item-desc skeleton" style="color: ${color}"><div class="info--item-desc-box"></div></div>
        </div>`);

        $(DOM).find(".info--item-desc-box").append(compile(_data.type, _data.value_text, _data.original, _data.value));

        if (_data.editable) {
            $(DOM).append(`<div class="info--item-edit"><i class="fa fa-edit"></i></div>`);
        }

        // 这里的Info__item_desc里面固定添加了一个div
        let $Info__item_desc = $(DOM).find(".info--item-desc").children("div");
        let $Info__item_edit = $(DOM).find(".info--item-edit");

        Object.defineProperty(data, "value_text", {
            get: function () {
                return _data.value_text;
            },
            set: function (val) {
                _data.value_text = val;
                $Info__item_desc.html(compile(_data.type, data.value_text, data.original, data.value));
            }
        });

        $Info__item_edit.on("click", function () {
            return onClickEdit(data);
        });

        Object.defineProperty(data, "el", {
            enumerable: false,
            get: function () {
                return DOM;
            }
        });

        // 如果display为false，需要隐藏此项
        if (!_data.display) {
            $(DOM).addClass("hide");
        }
        Object.defineProperty(data, "display", {
            get: function () {
                return _data.display;
            },
            set: function (val) {
                _data.display = val;
                if (_data.display) {
                    $(DOM).removeClass("hide");
                } else {
                    $(DOM).addClass("hide");
                }
            }
        });

        return data;
    };

    _this.infoItemPart = function (data, onClickEdit) {
        let _data = Object.assign({
            title: "",
            children: [],
            editable: false,
            display: false
        }, data);

        let DOM = Render.create(`<li class="info--parts">
            <div class="info--parts-title">
                <span class="info--parts-title-text">${_data.title}</span>
            </div>
        </li>`);

        let info_items = [];

        _data.children.map(info => {
            let infoItemDOM = _this.infoItemText(info, onClickEdit);
            if (infoItemDOM != undefined) {
                info_items.push(infoItemDOM.el);
            }
        });

        $(DOM).find(".info--item-edit").on("click", function () {
            onClickEdit(_data)
        });

        $(DOM).append(info_items);

        // 如果display为false，需要隐藏此项
        if (!_data.display) {
            $(DOM).addClass("hide");
        }
        Object.defineProperty(data, "display", {
            get: function () {
                return _data.display;
            },
            set: function (val) {
                _data.display = val;
                if (_data.display) {
                    $(DOM).removeClass("hide");
                } else {
                    $(DOM).addClass("hide");
                }
            }
        });

        return {
            el: DOM
        }
    };

    _this.process = function (data = {}) {
        let _data = Object.assign({
            title: "",
            process: [],
            onReply: function (D_id, A_id, message) {}
        }, data);

        let DOM = Render.create(`<div class="process"><ul class="process-box"></ul></div>`);
        let $Process_box = $(DOM).find(".process-box");
        let process_items = [];

        if (_data.title) {
            $Process_box.append(`<li style="margin-top:-2rem;line-height:3;">${_data.title}</li>`);
        }

        _data.process.map(process => {
            if (process.end === true) {
                process_items.push(_this.processEndItem().el);
                return;
            }

            let processItemDOM = _this.processItem({
                ...process,
                complain_visible: data.complain_visible,
                onReply: _data.onReply
            });

            if (processItemDOM != undefined) {
                process_items.push(processItemDOM.el);
            }
        });

        if (process_items.length > 0) {
            let last_process = process_items.slice(-1)[0];
            $(last_process).addClass("item-end");

            let data = _data.process.slice(-1)[0];
            if (data.status == "approval") {
                $(last_process).addClass("now");
            }
        }

        $Process_box.append(process_items);

        return {
            el: DOM
        };
    };

    _this.processItem = function (data = {}) {
        let _data = Object.assign({
            title: "",
            D_id: "",
            A_id: "",
            avatar: Config.default_avatar,
            label: "",
            name: "",
            status: "",
            time: "",
            type: "",
            type_text: "",
            // +yk: 审批意见 {name, content}
            complain: [],
            reply: [],
            persons: [],
            // +yk: 是否对发起人可见，如果不可见，发起人的留言按钮去掉
            complain_visible: true,
            onReply: function (D_id, A_id, message) {}
        }, data);

        _data.label_color = (function (type) {
            let _type = {
                copy: "warning",
                approval: _data.status == "refuse" ? "danger" : "primary",
                original: ""
            };
            return _type[type] || "";
        })(_data.type);

        let DOM = Render.create(`<li class="process--item">
            <div class="process--item-avatar skeleton"><img src="${_data.avatar}" alt="" srcset=""></div>
            <div class="process--item-desc skeleton">
                <div class="process--item-desc-box">
                    <div class="process--item-desc--title">${_data.title || _data.type_text}</div>
                    <div class="process--item-desc--time">${_data.time}</div>
                </div>
            </div>
        </li>`);

        let $Process_item_desc = $(DOM).find(".process--item-desc");
        let FirstDescDOM = Render.create(`<div class="process--item-desc-box">
            <div class="process--item-desc--name">
                <span class="process--item-desc--name-box">${_data.name}</span>
            </div>
            <div class="process--item-desc--status link-${_data.label_color}">${_data.label}</div>
        </div>`);

        // +yk: 除发起人不可见外，追加回复按钮
        // 可见时添加、不可见时部位流程的发起人节点添加
        if (_data.complain_visible || _data.type != "original") {
            $(FirstDescDOM).find(".process--item-desc--status").append(`<div class="commenting"><i class="fa fa-commenting"></i></div>`);
        }

        $(FirstDescDOM).find(".commenting").on("click", function (e) {
            e.stopPropagation();
            _this.reply({
                name: _data.name,
                onSubmit: function (message) {
                    _data.onReply(_data.D_id, _data.A_id, message);
                }
            }).render();
        });

        let personsDOM = Render.create(`<div style="display:none"></div>`);
        _data.persons.map(person => {
            let _status = {};
            let label = "";
            switch(_data.type) {
                case "approval":
                    _status = {
                        // 1: {
                        //     label: "审批中",
                        //     color: "primary"
                        // },
                        2: {
                            label: "已通过",
                            color: "primary"
                        },
                        3: {
                            label: "已拒绝",
                            color: "danger"
                        },
                    };
                    let __status = _status[person.status];
                    if (__status) {
                        label = `<span class="link-${__status.color}">（${__status.label}）</span>`;
                    }
                    break;
                case "copy":
                    if (person.readed) {
                        label = `<span class="link-warning">（已读）</span>`;
                    }
                    break;
            }

            $(personsDOM).append(`<p class="process--item-desc--name--detail">${person.name} ${label}</p>`);
        });

        if (_data.persons.length > 1) {
            $(FirstDescDOM).find(".process--item-desc--name-box").prepend(`<i class="fa fa-angle-right"></i>`);

            $(FirstDescDOM).on("click", function () {
                $(FirstDescDOM).toggleClass("on");
                $(personsDOM).toggle();
            });
        }


        let ComplainBoxDOM = [];
        _data.complain.map(r => {
            ComplainBoxDOM.push(Render.create(`<div class="process--item-desc-box">
                <div class="process--item-desc--append">${r.name}审批意见：${r.content}</div>
            </div>`));
        });

        let DescBoxDOM = [];
        _data.reply.map(r => {
            DescBoxDOM.push(Render.create(`<div class="process--item-desc-box">
                <div class="process--item-desc--append">${r.name}留言：${r.reply}</div>
            </div>`));
        });

        $(FirstDescDOM).find(".process--item-desc--name-box").append(personsDOM);
        $Process_item_desc.append(FirstDescDOM);
        // $Process_item_desc.append(personsDOM);
        $Process_item_desc.append(ComplainBoxDOM);
        $Process_item_desc.append(DescBoxDOM);


        return {
            el: DOM
        };
    };

    _this.processEndItem = function () {
        return {
            el: Render.create(`<li class="process--item item-end">
                <div class="process--item-avatar"><span>结束</span></div>
                <div class="process--item-desc"></div>
            </li>`)
        };
    }

    _this.opera = function (data = {}) {
        let _data = Object.assign({
            data: {},
            onTrash: function () {},
            onBell: function () {},
            onRetweet: function () {},
            onClose: function () {},
        }, data);

        let DOM = Render.create(`<div class="opera"></div>`);

        // 审批通过时显示作废按钮
        if (_data.data.approval_status == 1) {
            DOM = Render.create(`<div class="opera">
                <ul class="opera-box">
                    <li class="opera--item trash"><i class="fa fa-trash"></i> 撤销</li>
                    <li class="opera--item retweet"><i class="fa fa-retweet"></i> 再次发起</li>
                    ${_data.data.approval_identity == 1 ? '<li class="opera--item bell"><i class="fa fa-bell"></i> 提醒</li>' : ""}
                    <!-- <li class="opera--item print"><i class="fa fa-print"></i> 打印</li> -->
                </ul>
            </div>`);
        } else if (_data.data.approval_status == 2 && !_data.data.is_invalid) {
            DOM = Render.create(`<div class="opera">
                <ul class="opera-box">
                    <li class="opera--item retweet"><i class="fa fa-retweet"></i> 再次发起</li>
                    <li class="opera--item close"><i class="fa fa-times"></i> 作废</li>
                </ul>
            </div>`);
        } else {
            DOM = Render.create(`<div class="opera">
                <ul class="opera-box">
                    <li class="opera--item retweet"><i class="fa fa-retweet"></i> 再次发起</li>
                </ul>
            </div>`);
        }

        if (_data.data.category == 2) {
            $(DOM).find(".retweet").remove();
        }

        $(DOM).find(".trash").on("click", function () {
            _data.onTrash();
        });
        $(DOM).find(".bell").on("click", function () {
            _data.onBell();
        });
        $(DOM).find(".retweet").on("click", function () {
            _data.onRetweet();
        });
        $(DOM).find(".close").on("click", function () {
            _data.onClose();
        });
        $(DOM).find(".print").on("click", function () {
            _this.toast("请用电脑登录yun.5tree.cn进行打印操作").render();
        });

        return {
            el: DOM
        };
    };

    _this.tabbar = function (data = {}) {
        let _data = Object.assign({
            onPass: function (done) {},
            onRefuse: function (done) {}
        }, data);

        let DOM = Render.create(`<div class="tabbar">
            <div class="tabbar-box">
                <button class="btn btn-light refuse">拒绝</button>
                <button class="btn btn-primary pass">通过</button>
            </div>
        </div>`);

        $(DOM).find(".refuse").on("click", function () {
            _data.onRefuse();
        });

        $(DOM).find(".pass").on("click", function () {
            _data.onPass();
        });

        return {
            el: DOM
        };
    };


    let _CACHE_REPLY_DOMS;
    _this.reply = function (data = {}) {
        let _data = Object.assign({
            name: "",
            onSubmit: function () {}
        }, data);

        let DOM = Render.create(`<div class="reply">
            <div class="reply-box">
                <input type="text" class="reply-text" placeholder="回复@${_data.name}" />
                <button type="button" class="btn btn-success reply-submit">留言</button>
            </div>
        </div>`);

        let $Reply_text = $(DOM).find(".reply-text");

        Util.iosTextBlurScroll($Reply_text[0]);

        $(DOM).find(".reply-submit").on("click", function () {
            let text = $Reply_text.val();
            _data.onSubmit(text);
        });

        $(DOM).on("click", function () {
            $(DOM).removeClass("on");
            $("body").removeClass("clamp");
            setTimeout(() => {
                _CACHE_REPLY_DOMS.parentNode.removeChild(_CACHE_REPLY_DOMS);
                _CACHE_REPLY_DOMS = undefined;
            }, 300);
        });
        $(DOM).children().on("click", function (e) {
            e.stopPropagation();
        });

        return {
            el: DOM,
            render: function () {
                // 清除上一次显示的DOM
                if (_CACHE_REPLY_DOMS) {
                    _CACHE_REPLY_DOMS.parentNode.removeChild(_CACHE_REPLY_DOMS);
                }

                _CACHE_REPLY_DOMS = DOM;

                $("body").addClass("clamp");
                $("body").append(DOM);

                // 默认选中
                setTimeout(() => {
                    $(DOM).addClass("on");

                    setTimeout(() => {
                        $Reply_text.trigger("focus");
                    }, 200);
                }, 0);
            }
        };
    };

    _this.mediaBody = function (data) {
        console.log(data.original.type);
        let editator = Editate["editate_" + data.original.type](data);
        // let op = getListHtml(data.original, data.original.type, data.id);
        return {
            el: editator.el
        }
    };

    _this.complain = function (data = {}) {
        let _data = Object.assign({}, data);

        let DOM = Render.create(`<div>
            <textarea class="complain-text" data-media-form-name="complain" row="8" maxlength="1000"></textarea>
        </div>`);

        let $Complain_text = $(DOM).find(".complain-text");

        Util.iosTextBlurScroll($Complain_text[0]);

        if (_data.required) {
            $Complain_text.attr("placeholder", _data.approval_tips == "" ? "请输入审批意见（必填）" : _data.approval_tips);
        } else {
            $Complain_text.attr("placeholder", _data.approval_tips == "" ? "请输入审批意见" : _data.approval_tips);
        }

        return {
            el: DOM
        };
    };

    /**
     * 警告文字
     */
    _this.warningText = function (data = {}) {
        let _data = Object.assign({
            text: "",
            type: "success"
        }, data);
        let DOM = Render.create(`<div class="warning-text">
            <div class="warning-text-box"><p class="link-${_data.type}">${_data.text}</p></div>
        </div>`);
        return {
            el: DOM
        };
    };

    /**
     * 印章
     * 根据状态显示印章图片。
     * 2审批通过 3审批拒绝 4审批撤销
     */
    _this.stamp = function (status) {
        let stamps = {
            "2": "./assets/images/sptg.png",
            "3": "./assets/images/spjj.png",
            "4": "./assets/images/spcx.png",
            "7": "./assets/images/spzf.png",
        };

        let stamp = stamps[status];

        if (stamp) {
            let DOM = Render.create(`<div class="stamp"><img src="${stamp}" alt=""/></div>`);

            return {
                el: DOM
            }
        }
    };

    return new Component;
})();